package com.songlanyun.modules.sensitive.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.common.utils.SensiUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.songlanyun.modules.sensitive.dao.SystemSensitiveWordDao;
import com.songlanyun.modules.sensitive.entity.SystemSensitiveWordEntity;
import com.songlanyun.modules.sensitive.service.SystemSensitiveWordService;

import javax.annotation.Resource;


@Service("yxtSystemSensitiveWordService")
public class SystemSensitiveWordServiceImpl extends ServiceImpl<SystemSensitiveWordDao, SystemSensitiveWordEntity> implements SystemSensitiveWordService {


    @Resource
    private SystemSensitiveWordDao sensiDao;
    @Resource
    SensiUtil sensiUtil;


    /**
     * 列表
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String source = MapUtil.getStr(params, "source");
        IPage<SystemSensitiveWordEntity> page = this.page(
                new Query<SystemSensitiveWordEntity>().getPage(params),
                new LambdaQueryWrapper<SystemSensitiveWordEntity>()
                        .eq(StringUtils.isNotBlank(source), SystemSensitiveWordEntity::getSource, source)
        );
        return new PageUtils(page);
    }

    /**
     * 过滤敏感词
     *
     * @param text
     * @return
     */
    @Override
    public String filter(String text) {
        return sensiUtil.filter(text);
    }

    @Override
    public List<String> getSources() {
        return sensiDao.getSources();
    }


    /**
     * 批量添加附加敏感词
     *
     * @param arr
     */
    @Override
    public void put(String[] arr) {
        List<SystemSensitiveWordEntity> list = new ArrayList<>();
        //判断添加的敏感词在数据库中存不存在，不存在则添加
        for (String s : arr) {
            int count = this.count(
                    new LambdaQueryWrapper<SystemSensitiveWordEntity>()
                            .eq(SystemSensitiveWordEntity::getSource, s)
            );
            //不存在则添加
            if (count == 0) {
                SystemSensitiveWordEntity entity = new SystemSensitiveWordEntity();
                entity.setSource(s);
                list.add(entity);
            }
        }

        //批量添加
        if (list.size() > 0) {
            this.saveBatch(list);
        }
    }

    @Override
    public void flush() {
        //查询数据库中所有的附加敏感词
        List<String> texts = getSources();
        //将敏感词数据刷新到缓存中
        sensiUtil.flushList(texts);
    }

}
